package com.bishe.app.core.utils;

import com.bishe.app.core.config.SessionInterceptor;
import com.bishe.app.modules.user.entity.User;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created : 2023/12/22, 20:19
 *
 * @author : jeffrey.hu
 **/
@Component
public class AppRunnerUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;


    public static <T> T getBean(Class<T> clz) {
        return applicationContext.getBean(clz);
    }

    public static String getEnv(String key){
        return getBean(Environment.class).getProperty(key);
    }

    public static List<String> getSuperNames(){
        String env = getEnv("super.usernames");
        return Arrays.stream(env.split(",")).collect(Collectors.toList());
    }


    public static User getUser() {
        return getBean(SessionInterceptor.class).getUserFromToken();
    }

    public static String getHeader(String key) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader(key);
        return token;
    }


    public static String token() {
        return getHeader("X-Token");
    }

    public static String getUploaderPath() {
        String path = System.getProperty("user.dir");
        File upload = new File(path, "/images/");
        if (!upload.exists()) upload.mkdirs();
        return upload.getAbsolutePath();
    }


    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        applicationContext = ctx;
    }
}
